package com.prim.jmm;

import java.util.concurrent.CountDownLatch;

/**
 * 演示重排序
 * "直到达到某个条件才停止" 测试小概率事件
 */
public class OutOfOrderExecution {

    private static int a, b = 0;

    private static int x, y = 0;

    private static int index = 0;

    public static void main(String[] args) throws InterruptedException {
        //定义闸门
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (; ; ) {
            index++;
            a = 0;
            b = 0;
            x = 0;
            y = 0;
            Thread oneThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    a = 1;

                    x = b;
                }
            });
            Thread twoThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    b = 1;

                    y = a;
                }
            });
            oneThread.start();
            twoThread.start();
            //放开闸门
            countDownLatch.countDown();
            oneThread.join();
            twoThread.join();
            String result = "第" + index + "次(x:" + x + " y:" + y + ")";
            if (x == 0 && y == 0) {
                System.out.println(result);
                break;
            } else {
                System.out.println(result);
            }
        }
    }
}
